Object Initializers in C#

With C# 3.0, It is very easy to start both the objects and collections. Consider this simple car square, where we use the automatic properties described in the previous chapter:


class Car
{
    public string Name { get; set; }
    public Color Color { get; set; }
}

Now, in C# 2.0, we would have to write a piece of code like this to create a Car instance and set its properties:


Car car = new Car();
car.Name = "Chevrolet Corvette";
car.Color = Color.Yellow;

It's just fine really, but with C# 3.0, it can be done a bit more cleanly, thanks to the new object initializer syntax:


Car car = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow };

As you can see, we use a set of curly brackets after starting a new car object, and within them, we have access to all the public properties of the car class. It saves little typing, and also saves a small space. The good part is that it can also be nested. Consider the following example, where we add a new complex property in the car category, such as:


class Car
{
    public string Name { get; set; }
    public Color Color { get; set; }
    public CarManufacturer Manufacturer { get; set; }
}

class CarManufacturer
{
    public string Name { get; set; }
    public string Country { get; set; }
}

To initialize a new car with C# 2.0, we would have to do something like this:


Car car = new Car();
car.Name = "Corvette";
car.Color = Color.Yellow;
car.Manufacturer = new CarManufacturer();
car.Manufacturer.Name = "Chevrolet";
car.Manufacturer.Country = "USA";

With C# 3.0, we can do it like this instead:


Car car = new Car { 
                Name = "Chevrolet Corvette", 
                Color = Color.Yellow, 
                Manufacturer = new CarManufacturer { 
                    Name = "Chevrolet", 
                    Country = "USA" 
                } 
            };

Or in case you're not too worried about readability, like this:


Car car = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow, Manufacturer = new CarManufacturer { Name = "Chevrolet", Country = "USA" } };

Just like with the automatic properties, this is syntactical sugar - you can either use it, or just stick with the old, fashioned way of doing things.